package com.myproject.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;

/**
 * 图形验证码工具类
 */
public class CaptchaUtil {
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;
    private static final String CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";

    /**
     * 生成验证码图片和对应验证码
     * @return 数组，第一个元素是base64编码的图片，第二个元素是验证码
     */
    public static String[] generateCaptcha() {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        
        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        
        // 绘制干扰线
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            g.setColor(getRandomColor());
            g.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), 
                      random.nextInt(WIDTH), random.nextInt(HEIGHT));
        }
        
        // 生成随机验证码
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            String ch = String.valueOf(CODES.charAt(random.nextInt(CODES.length())));
            captcha.append(ch);
            
            // 绘制验证码
            g.setColor(getRandomColor());
            g.setFont(new Font("Arial", Font.BOLD, 24));
            g.drawString(ch, 25 * i + 10, 28);
        }
        
        g.dispose();
        
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "JPEG", baos);
            String base64Image = "data:image/jpeg;base64," + 
                               Base64.getEncoder().encodeToString(baos.toByteArray());
            return new String[]{base64Image, captcha.toString()};
        } catch (IOException e) {
            throw new RuntimeException("生成验证码失败", e);
        }
    }

    private static Color getRandomColor() {
        Random random = new Random();
        return new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200));
    }
}